package com.myjpa.generate;

import jdk.nashorn.internal.ir.ObjectNode;

import java.sql.*;

/**
 * @author: yaoll
 * @date: 2020-09-08
 * @verison: 1.0
 */
public class JdbcGeneratorUtils {

	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static String sql = "select column_name, data_type, column_key, column_comment, numeric_precision, numeric_scale " +
			"from information_schema.columns where table_schema = ? and table_name = ?";

	public static final void initAttribute(String url, String username, String password, String database, GenerateContext ctx) {

		try {
			Connection connection = DriverManager.getConnection(url, username, password);
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, database);
			ps.setString(2, ctx.getTableName());
			ResultSet rs = ps.executeQuery();

			while (rs.next()) {

				String name = rs.getString("column_name");
				String type = rs.getString("data_type");
				String key = rs.getString("column_key");
				String comment = rs.getString("column_comment");
				Integer precision = rs.getInt("numeric_precision");
				Integer scale = rs.getInt("numeric_scale");

				ctx.addAttribute(toCamel(name), toJavaType(type, precision, scale));

				System.out.println(name + " " + type + " " + key + " " + comment);

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private static String toCamel(String source) {
		if (source == null) {
			return source;
		}

		String[] arr = source.split("_");
		StringBuilder result = new StringBuilder();
		for (String item : arr) {
			result.append(item.substring(0, 1).toUpperCase()).append(item.substring(1).toLowerCase());
		}
		String target = result.toString();
		return target.substring(0, 1).toLowerCase() + target.substring(1);
	}

	private static Class toJavaType(String type, Integer precision, Integer scale) {
		if ("varchar".equalsIgnoreCase(type) || "text".equalsIgnoreCase(type)) {
			return String.class;
		} else if ("int".equalsIgnoreCase(type)) {
			return precision > 11 ? Long.class : Integer.class;
		} else if ("double".equalsIgnoreCase(type) || "decimal".equalsIgnoreCase(type)) {
			return Double.class;
		} else if ("datetime".equalsIgnoreCase(type) || "timestamp".equalsIgnoreCase(type)) {
			return Date.class;
		} else if ("json".equalsIgnoreCase(type)) {
			return ObjectNode.class;
		}

		throw new RuntimeException("type[" + type + "] not mapping");
	}


}
